package com.gitee.kenewstar.migration.api;

import com.gitee.kenewstar.migration.constants.Const;
import com.gitee.kenewstar.migration.core.DataMigrationBeanHandler;
import com.gitee.kenewstar.migration.entity.CommonDto;
import com.gitee.kenewstar.migration.entity.CommonResponse;
import com.gitee.kenewstar.migration.util.ExcelUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @author kenewstar
 */
@Slf4j
@RestController
@RequestMapping("/common")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class CommonApi {

    private final DataMigrationBeanHandler dataMigrationBeanHandler;

    @PostMapping("/migration/{functionCode}")
    public CommonResponse migration(@PathVariable("functionCode") String functionCode,
                                    @RequestBody List<CommonDto> list) {
        log.info("===================functionCode======================> {}", functionCode);
        val function = this.dataMigrationBeanHandler.getFunction(functionCode);
        Assert.notNull(function, "函数不存在");
        return function.migration(list);
    }

    @PostMapping("/migration/upload/{functionCode}")
    public CommonResponse migrationUpload(@PathVariable("functionCode") String functionCode,
                                          @RequestPart(Const.FILE) MultipartFile file) {
        log.info("===================functionCode======================> {}", functionCode);
        val function = this.dataMigrationBeanHandler.getFunction(functionCode);
        Assert.notNull(function, "函数不存在");
        return function.migration(ExcelUtil.filterReadData(file, CommonDto.class));
    }

}
